package com.hu.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hu.reggie.dto.DishDto;
import com.hu.reggie.mapper.DishMapper;
import com.hu.reggie.pojo.Dish;
import com.hu.reggie.pojo.DishFlavor;
import com.hu.reggie.service.DishFlavorService;
import com.hu.reggie.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishFlavorService dishFlavorService;

    // 新增菜品，同时插入菜品口味数据
    @Override
    @Transactional  // 多表操作开启事务
    public void saveWithFlavor(DishDto dishDto) {
        // 菜品信息存储,save方法会自动生成id并赋值给dishDto
        this.save(dishDto);
        Long dishId=dishDto.getId();
        // 保存菜品口味数据
        List<DishFlavor> dishFlavorList=dishDto.getFlavors();
        dishFlavorList=dishFlavorList.stream().map((item) ->{
            item.setDishId(dishId);
            return item;
        }).collect(Collectors.toList());
        dishFlavorService.saveBatch(dishFlavorList);
    }

    // 根据id查询菜品信息和对应的可以信息
    @Override
    @Transactional
    public DishDto getByIdWithFlavor(Long id) {
        DishDto dishDto=new DishDto();
        // 查询菜品基本信息
        Dish dish = this.getById(id);

        // 将dish拷贝到dishDto中
        BeanUtils.copyProperties(dish,dishDto);

        // 查询菜品对应的口味信息
        LambdaQueryWrapper<DishFlavor> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,dish.getId());
        List<DishFlavor> dishFlavors = dishFlavorService.list(queryWrapper);

        // 设置口味信息
        dishDto.setFlavors(dishFlavors);
        return dishDto;
    }

    // 修改菜品信息和口味信息
    @Override
    public void updateDishByIdFlavor(DishDto dishDto) {
        // 更新Dish表
        this.updateById(dishDto);

        // 先清理当前菜品对应的口味数据，然后存储修改后的数据
        // 清理
        LambdaQueryWrapper<DishFlavor> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,dishDto.getId());
        dishFlavorService.remove(queryWrapper);

        // 存储
        List<DishFlavor> dishFlavors=dishDto.getFlavors();
        dishFlavors=dishFlavors.stream().map(item ->{
            item.setDishId(dishDto.getId());
            return item;
        }).collect(Collectors.toList());

        dishFlavorService.saveBatch(dishFlavors);
    }
}
